import jwt  from "jsonwebtoken";
import User from "../models/User.js";
import asyncHandler from "express-async-handler"

/**
 * 登录保护
 */
export const protect = asyncHandler(async(req,res,next) => {
  let token = req.headers.authorization
  if(token && token.startsWith("Bearer")) {
    try {
      token = token.split(" ")[1]
      /* 解析token */
      const {id} = jwt.verify(token, process.env.JWT_SECRET)
      req.user = await User.findById(id).select('-password')
      next()
    } catch(err) {
      console.log(err)
      res.status(503)
      throw new Error('token验证失败')
    }
  } else {
    res.status(503)
    throw new Error('token验证失败')
  }
})

/**
 * 管理员保护
 */
 export const admin = asyncHandler(async(req,res,next) => {
  if(req.user && req.user.isAdmin)  {
    next()
  } else {
    res.status(504)
    throw new Error('不是管理员')
  }
})